package com.taxsystem.chengwenzhi.personal_notices;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import com.main.taxsystem.R;
import com.main.taxsystem.TableInfoSet;
import com.main.taxsystem.TableInfoSet.PersonalNoticesTableInfo;
import com.main.taxsystem.TaxSystemContentProvider;

import android.app.ActionBar;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.Window;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.taxsystem.tool.CommonOperations;
import com.taxsystem.tool.GetRequestTask;
import com.taxsystem.tool.HttpUtil;

public class PersonalNoticeShowActivity extends Activity{
	private static final String TAG = "PersonalNotationShowActivity";
	private static String HOST = null;
	private String noticeId = null;
	private String noticeCreateTime = null;
	private String noticeTitle = null;
	private String noticeContent = null;
	private TextView titleView = null;
	private TextView createTimeView = null;
	private TextView contentView = null;
	private static String SERVER_URL = null;
	private Handler mHandler = null;
	private static final String API = "/notation/findbyid?notationid=";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.v(TAG,"onCreate() begin");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.personal_notices_2);
		
		init();

		HOST = getResources().getString(R.string.host);
		
		Intent parent = getIntent();
		noticeId = parent.getStringExtra(PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_ID);
		
		mHandler = new MyHandler(getMainLooper());
		new MyThread().start();
	}
	
	private void init(){
		//init actionbar
		ActionBar bar = getActionBar();
        bar.setHomeButtonEnabled(true);
        bar.setIcon(R.drawable.actionbar_icon);
        bar.setBackgroundDrawable(new ColorDrawable(0xff34a4f7));
        
        createTimeView = (TextView) this.findViewById(R.id.notation_create_time);
        titleView = (TextView) this.findViewById(R.id.notation_title);
		contentView = (TextView) this.findViewById(R.id.notation_content);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}
	
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 更新noticeContent和数据库
	 */
	void parseJSON(String jsonString){
		try {
			JSONObject object = new JSONObject(jsonString);
			JSONObject dataObject = object.getJSONObject("data");
			noticeContent = dataObject.getString("content");
			ContentValues values = new ContentValues();
			values.put(PersonalNoticesTableInfo.COLUMEN_NAME_CONTENT, noticeContent);
			getContentResolver().update(TaxSystemContentProvider.URI_PERSIONAL_NOTICES, values, 
					PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_ID+"='"+noticeId+"'", null);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private class MyHandler extends Handler{

		public MyHandler(Looper looper){
			super(looper);
		}
		
		@Override
		public void handleMessage(Message msg) {
			Log.v(TAG,"MyHandler::handleMessage()");
			titleView.setText(noticeTitle);
			createTimeView.setText(noticeCreateTime);
			contentView.setText(noticeContent);
			setProgressBarIndeterminateVisibility(false);
		}
		
	}
	
	private class MyThread extends Thread {

		public String pullContent(){
			Log.v(TAG,"MyThread::pullContent()");
			String url = HOST+API+noticeId;
			Log.v(TAG,"MyThread::pullContent():url="+url);
			String result = null;
			HttpURLConnection conn = null;
			try {
				conn = (HttpURLConnection) new URL(url).openConnection();
				InputStream in = new BufferedInputStream(
						conn.getInputStream());
				ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
		        byte[] data = new byte[255];  
		        int count = -1;  
		        while((count = in.read(data,0,255)) != -1)  
		            outStream.write(data, 0, count);  
		        data = null;  
				result = new String(outStream.toByteArray(),"UTF-8");
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				conn.disconnect();
			}
			return result;
		}
		@Override
		public void run() {
			setProgressBarIndeterminateVisibility(true);
			ContentResolver cr = PersonalNoticeShowActivity.this
					.getContentResolver();
			Cursor cursor = cr.query(
					TaxSystemContentProvider.URI_PERSIONAL_NOTICES,
					new String[] {
							PersonalNoticesTableInfo.COLUMEN_NAME_CREATE_TIME,
							PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_TITLE,
							PersonalNoticesTableInfo.COLUMEN_NAME_CONTENT },
					PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_ID + "='"
							+ noticeId+"'", null, null);
			cursor.moveToFirst();
			noticeContent = cursor
					.getString(cursor
							.getColumnIndex(PersonalNoticesTableInfo.COLUMEN_NAME_CONTENT));
			noticeTitle = cursor
					.getString(cursor
							.getColumnIndex(PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_TITLE));
			noticeCreateTime = cursor
					.getString(cursor
							.getColumnIndex(PersonalNoticesTableInfo.COLUMEN_NAME_CREATE_TIME));

			Log.v(TAG,"noticeContent="+noticeContent);
			if (null==noticeContent || "".equals(noticeContent))// 内容为空,从服务器拉取数据
				parseJSON(pullContent());
			
			cursor.close();
			mHandler.sendEmptyMessage(0);
		}
	}
}
